<template>
  <a-spin class="statist-wapper" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l">
        <span>站点：</span>
        <a-select
          style="width:160px;margin-right:15px;"
          show-search
          :allowClear="true"
          placeholder="请选择站点"
          v-model="search.locationIdList"
          @change="handleByQueryCond"
          :filter-option="filterOption"
        >
          <a-select-option v-for="(item, index) in locationListData" :key="index + '-' + item.id" :value="item.id">{{ item.city }}</a-select-option>
        </a-select>
        <span>日期：</span>
        <a-range-picker style="margin-right:15px;" @change="handleByQueryCond" v-model="search.selectDate" />
        <a-button type="primary" @click="chooseDay(1)" style="background:#1d6fe9">昨天</a-button>
        <a-button type="primary" @click="chooseDay(2)" style="background:#1d6fe9">近7天</a-button>
        <a-button type="primary" @click="chooseDay(3)" style="background:#1d6fe9">近30天</a-button>
      </div>

      <div class="r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
        <a-button type="primary" @click="exportData" style="background:#34C025;border-color:#34C025;">导出excel</a-button>
      </div>
    </div>
    <div class="all-data">
      <div class="data-item total-data">
        <div class="img-box" v-show="search.selectDate && search.selectDate.length === 0"><img src="@/assets/images/statist/icon_sjtj_zls@3x.png" alt="" /></div>
        <div class="data-item-item">
          <p class="number-p">
            <!-- {{ (totalData.totalMoney || 0) | fenToYuan }} -->
            <a-statistic :value="(totalData.totalMoney || 0) | fenToYuan" />
          </p>
          <p class="text-p">总流水</p>
        </div>
        <!-- <div class="data-item-item">
          <p class="number-p">{{ (totalData.completeMoney || 0) | fenToYuan }}</p>
          <p class="text-p">已核销金额</p>
        </div> -->
        <!-- <div class="data-item-item">
          <p class="number-p">{{ (totalData.refundMoney || 0) | fenToYuan }}</p>
          <p class="text-p">已退款金额</p>
        </div> -->
        <div class="data-item-item">
          <p class="number-p">
            <a-statistic :value="totalData.totalOrderNum" />
            <!-- {{ totalData.totalOrderNum || 0 }} -->
          </p>
          <p class="text-p">总订单</p>
        </div>
        <!-- <div class="data-item-item">
          <p class="number-p">{{ totalData.completeOrderNum || 0 }}</p>
          <p class="text-p">已核销订单</p>
        </div>
        <div class="data-item-item">
          <p class="number-p">{{ totalData.refundOrderNum || 0 }}</p>
          <p class="text-p">已退款订单</p>
        </div> -->
        <div class="data-item-item">
          <p class="number-p">
            <!-- {{ totalData.productNum || 0 }} -->
            <a-statistic :value="totalData.productNum" />
          </p>
          <p class="text-p">商品数量</p>
        </div>
        <div class="data-item-item">
          <p class="number-p">
            <a-statistic :value="(totalData.profitMoney || 0) | fenToYuan" />
          </p>
          <p class="text-p">总利润</p>
        </div>
      </div>
      <div class="data-item today-data">
        <div class="img-box"><img src="@/assets/images/statist/icon_sjtj_jr@3x.png" alt="" /></div>
        <div class="data-item-item">
          <p class="number-p">
            <!-- {{ (todayData.totalMoney || 0) | fenToYuan }} -->
            <a-statistic :value="(todayData.totalMoney || 0) | fenToYuan" />
          </p>
          <p class="text-p">今日总流水</p>
        </div>
        <!-- <div class="data-item-item">
          <p class="number-p">{{ (todayData.completeMoney || 0) | fenToYuan }}</p>
          <p class="text-p">今日已核销金额</p>
        </div> -->
        <!-- <div class="data-item-item">
          <p class="number-p">{{ (todayData.refundMoney || 0) | fenToYuan }}</p>
          <p class="text-p">今日已退款金额</p>
        </div> -->
        <div class="data-item-item">
          <p class="number-p">
            <a-statistic :value="todayData.totalOrderNum || 0" />
          </p>
          <p class="text-p">今日总订单</p>
        </div>
        <!-- <div class="data-item-item">
          <p class="number-p">{{ todayData.completeOrderNum || 0 }}</p>
          <p class="text-p">今日已核销订单</p>
        </div>
        <div class="data-item-item">
          <p class="number-p">{{ todayData.refundOrderNum || 0 }}</p>
          <p class="text-p">今日已退款订单</p>
        </div> -->
        <div class="data-item-item">
          <p class="number-p">
            <a-statistic :value="todayData.productNum || 0" />
          </p>
          <p class="text-p">今日商品数量</p>
        </div>
        <div class="data-item-item">
          <!-- <p class="number-p">
            <a-statistic :value="(todayData.profitMoney || 0) | fenToYuan" />
          </p>

          <p class="text-p">今日利润</p> -->
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="siteDataList" :scroll="{ x: 900, y: tableHeight }" rowKey="locationId"></a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;text-align:right;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { statistData, locationList, exportStatistList } from '@/service'
import upload from '@/components/upload/upload'
import { safeDiv, getExcel } from '@/util'
// import {} from '@/service/ksService'
import moment from 'moment'
export default {
  name: 'kwaiPointStatistics',
  data() {
    return {
      moment,
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // table数据查询条件
      search: {
        // 1-待审核;2-已通过;3-已驳回
        locationIdList: undefined,
        selectDate: []
      },
      // 站点统计列表
      siteDataList: [],
      // 主播列表总数据条数
      anchorTotal: 0,
      // 今天统计数
      totalData: {},
      // 总统计数
      todayData: {},
      // 站点列表
      locationListData: []
    }
  },

  components: {
    upload
  },

  computed: {
    // table配置
    tableColumns() {
      return [
        { title: '站点', width: 150, dataIndex: 'city' },
        {
          title: '总流水',
          width: 120,
          dataIndex: 'totalMoney',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        {
          title: '已核销金额',
          width: 120,
          dataIndex: 'completeMoney',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        {
          title: '已退款金额',
          width: 120,
          dataIndex: 'refundMoney',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        { title: '总订单', width: 120, dataIndex: 'totalOrderNum' },
        { title: '已核销订单', width: 120, dataIndex: 'completeOrderNum' },
        { title: '已退款订单', width: 120, dataIndex: 'refundOrderNum' },
        { title: '商品数量', width: 120, dataIndex: 'productNum' },
        {
          title: '总利润',
          width: 120,
          dataIndex: 'profitMoney',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        }
      ]
    }
  },

  methods: {
    chooseDay(type = '') {
      let chooseDays = []
      const { getDay } = this
      switch (type) {
        case 1:
          chooseDays = [getDay(-1), getDay(-1)]
          break
        case 2:
          chooseDays = [getDay(-6), getDay(0)] || []
          break
        case 3:
          chooseDays = [getDay(-29), getDay(0)] || []
          break
        default:
          chooseDays = []
          break
      }
      this.search.selectDate = chooseDays
      this.handleByQueryCond()
    },
    getDay(day) {
      var today = new Date()
      var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(targetday)
      var tYear = today.getFullYear()
      var tMonth = today.getMonth()
      var tDate = today.getDate()
      tMonth = this.doHandleMonth(tMonth + 1)
      tDate = this.doHandleMonth(tDate)
      return tYear + '-' + tMonth + '-' + tDate
    },
    doHandleMonth(month) {
      var m = month
      if (month.toString().length === 1) {
        m = '0' + month
      }
      return m
    },
    // 站点列表
    async getLocationList() {
      await locationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationIdList = undefined, selectDate } = this.search

      return {
        pageIndex,
        pageSize,
        locationIdList: locationIdList ? [locationIdList] : [],
        dayStart: selectDate[0] ? moment(selectDate[0]).format('YYYYMMDD') : undefined,
        dayEnd: selectDate[1] ? moment(selectDate[1]).format('YYYYMMDD') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, locationIdList = undefined, dayStart, dayEnd } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          locationIdList: locationIdList ? [locationIdList] : [],
          selectDate: dayStart && dayEnd ? [moment(Number(dayStart)), moment(Number(dayEnd))] : []
          //  selectDate: beginTime ? Number(beginTime) : null,
          //  endTime: endTime ? Number(endTime) : null,
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * 获取数据统计列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      statistData(this.getParams())
        .then((rs) => {
          const { pageStatistics = {}, todayStatistics = {}, totalStatistics = {} } = rs || {}
          this.siteDataList = Object.freeze(pageStatistics.detailList) || []
          this.pagination.total = pageStatistics.total || 0
          this.totalData = totalStatistics
          this.todayData = todayStatistics
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    exportData() {
      const query = this.getParams()
      exportStatistList(query)
        .then((res) => {
          getExcel(`站点产品统计列表.xlsx`, res)
        })
        .catch(() => {
          this.$messageSend.error('数据量过大 请重新筛选！')
        })
    }
  },

  mounted() {
    this.getLocationList()
    this.setSearch()
    this.query()
  },

  filters: {
    // 获取直播平台
    getPlatform(val) {
      if (!val) return '无'
      return val === 1 ? '抖音' : '快手'
    },
    // 处理分-元
    fenToYuan(val) {
      if (!val) return 0
      return (val / 100).toFixed(2)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-spin-container {
  width: 100%;
}
p {
  margin: 0;
}
.statist-wapper {
  padding: 16px;
}
.all-data {
  background: #ffffff;
  box-shadow: 1px 0px 0px 0px #f6f6f6;
  border-radius: 4px;
  margin: 16px 0;
  border: 1px solid #f6f6f6;
  .data-item {
    position: relative;
    display: flex;
    padding-left: 50px;
    .img-box {
      position: absolute;
      left: 0;
      top: 0;
    }

    &-item {
      width: calc(100% / 4);
      padding: 16px 0;
      text-align: center;
      border-right: 1px solid #f6f6f6;
    }
    &-item:last-child {
      border: none;
    }
  }
  .total-data {
    border-bottom: 1px solid #f6f6f6;
    .img-box {
      width: 45px;
      height: 40px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .today-data {
    .img-box {
      width: 50px;
      height: 50px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
.number-p {
  font-size: 22px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 30px;
}
.text-p {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #666666;
  line-height: 20px;
}
</style>
